<template>
  <view class="warehouse-container">
    <!-- A. 页面头部 -->
    <view class="page-header">
      <text class="page-title">配料计划</text>
    </view>

    <!-- C. 查询/选择区 -->
    <view class="search-section">
      <view class="section-header">
        <text class="section-title">查询条件</text>
        <view class="time-filter-buttons">
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'today' }"
            @tap="
              handleTimeChange('today');
              handleSearch();
            "
          >
            当日
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'yesterday' }"
            @tap="
              handleTimeChange('yesterday');
              handleSearch();
            "
          >
            昨日
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'tomorrow' }"
            @tap="
              handleTimeChange('tomorrow');
              handleSearch();
            "
          >
            明日
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'week' }"
            @tap="
              handleTimeChange('week');
              handleSearch();
            "
          >
            近7天
          </button>
        </view>
      </view>

      <!-- Tab切换 -->
      <view class="tab-container">
        <view
          class="tab-item"
          :class="{ active: activeTab === 'furnace' }"
          @tap="activeTab = 'furnace'"
        >
          炉次计划
        </view>
        <view
          class="tab-item"
          :class="{ active: activeTab === 'burden' }"
          @tap="activeTab = 'burden'"
        >
          配料计划
        </view>
      </view>

      <!-- 炉次计划Tab -->
      <view v-if="activeTab === 'furnace'" class="tab-content">
        <view class="table-container">
          <view class="table-header">
            <text class="table-title">炉次计划列表</text>
            <text class="table-subtitle"
              >每次最多查询100条数据，更多请滑动底部加载</text
            >
          </view>
          <scroll-view
            class="table-scroll"
            scroll-y
            scroll-x
            @scrolltolower="onReachBottom"
            @scroll="handleTableScroll"
            ref="tableScroll"
          >
            <view class="table-scroll-container">
              <view class="table-scroll-wrapper">
                <view class="table-content">
                  <view class="table-row table-header-row">
                    <view class="table-cell header-cell">炉次号</view>
                    <view class="table-cell header-cell">钢种</view>
                    <view class="table-cell header-cell">总重</view>
                    <view class="table-cell header-cell">全新料重</view>
                    <view class="table-cell header-cell">棒重</view>
                    <view class="table-cell header-cell">损耗</view>
                    <view class="table-cell header-cell">计划日期</view>
                  </view>
                  <view
                    v-for="(item, index) in furnaceTableData"
                    :key="index"
                    class="table-row"
                    @tap="selectFurnace(item)"
                  >
                    <view class="table-cell">{{ item.recordNo || "-" }}</view>
                    <view class="table-cell">{{ item.steelGrade || "-" }}</view>
                    <view class="table-cell">{{
                      (item.totalbachWeight || 0).toFixed(3)
                    }}</view>
                    <view class="table-cell">{{
                      (item.newmaterialWeight || 0).toFixed(3)
                    }}</view>
                    <view class="table-cell">{{
                      (item.barWeight || 0).toFixed(3)
                    }}</view>
                    <view class="table-cell">{{
                      (item.lossWeight || 0).toFixed(3)
                    }}</view>
                    <view class="table-cell">{{
                      item.createTime
                        ? dateHelperApi.formatDate(item.createTime)
                        : "-"
                    }}</view>
                  </view>
                </view>
              </view>
              <view
                class="scroll-hint"
                :class="{ show: showScrollHint }"
                v-if="showScrollHint"
              >
                <text class="hint-icon">→</text>
                <text>横向滑动查看更多信息</text>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>

      <!-- 配料计划Tab -->
      <view v-if="activeTab === 'burden'" class="tab-content">
        <view class="plan-table-container">
          <view class="plan-table-header">
            <text class="section-title">汇总统计</text>
            <view class="statistics-info">
              <text class="stat-item">总计划量: {{ totalPlanWeight }} KG</text>
            </view>
          </view>
          <view class="furnace-info">
            <view class="furnace-info-content">
              <text class="furnace-info-text"
                >选中炉次：{{
                  selectedFurnace ? selectedFurnace.recordNo : "请先选择炉次"
                }}</text
              >
              <view
                v-if="selectedFurnace && burdenTableData.length > 0"
                class="furnace-extra-info"
              >
                <text class="furnace-extra-item"
                  >钢种: {{ burdenTableData[0].steelGrade || "-" }}</text
                >
                <text class="furnace-extra-item"
                  >配料编号: {{ burdenTableData[0].batchNo || "-" }}</text
                >
              </view>
            </view>
          </view>
          <scroll-view class="burden-scroll" scroll-y>
            <view
              v-for="(item, index) in burdenTableData"
              :key="index"
              class="burden-card"
            >
              <!-- 物料名称 - 突出显示 -->
              <view class="material-header">
                <text class="material-name">{{
                  item.materialName || "-"
                }}</text>
                <view class="material-proportion-badge"
                  >{{
                    calculateProportion(item.materialWeight).toFixed(1)
                  }}%</view
                >
              </view>

              <!-- 重量和占比信息 - 主要展示区域 -->
              <view class="material-main-info">
                <view class="weight-section">
                  <text class="weight-label">重量</text>
                  <text class="weight-value">{{
                    (item.materialWeight || 0).toFixed(3)
                  }}</text>
                  <text class="weight-unit">KG</text>
                </view>

                <!-- 占比进度条 -->
                <view class="proportion-section">
                  <view class="proportion-header">
                    <text class="proportion-label">占比</text>
                    <text class="proportion-value"
                      >{{
                        calculateProportion(item.materialWeight).toFixed(2)
                      }}%</text
                    >
                  </view>
                  <view class="proportion-bar">
                    <view
                      class="proportion-fill"
                      :style="{
                        width: calculateProportion(item.materialWeight) + '%',
                      }"
                    ></view>
                  </view>
                </view>
              </view>
            </view>

            <!-- 空数据提示 -->
            <view v-if="burdenTableData.length === 0" class="empty-tip">
              <text>暂无配料计划数据</text>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 导入API方法
import { SxBatchApi } from "@/api/pp/sxbatch";
import { getProcessOptions } from "@/api/md/process";

import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";
export default {
  name: "StockIn",
  data() {
    return {
      // 表单数据
      formData: {
        currentDate: dateHelperApi.getCurrentDate(),
        processCode: "",
        processName: "",
      },

      // 当前工序信息
      currentProcess: {
        processCode: "",
        processName: "请选择生产工序",
      },
      // 班次班组信息
      workShift: "", // 班次
      workClass: "", // 班组
      // 搜索表单
      searchForm: {
        materialCode: "",
        materialName: "",
      },
      // 时间筛选器
      timeFilter: "today",
      // 时间范围
      timeRange: {
        startTime: "",
        endTime: "",
      },

      // 表格数据
      detailTableData: [],
      detailLoading: false,
      // 加载状态
      loading: false,
      // 分页与刷新
      refreshing: false,
      pageNum: 1,
      hasMore: true,
      // 工序选项列表
      processOptions: [],
      // 当前工序索引
      currentProcessIndex: -1,

      // Tab相关数据
      activeTab: "furnace", // 当前激活的tab
      furnaceTableData: [], // 炉次计划数据
      burdenTableData: [], // 配料计划数据
      selectedFurnace: null, // 选中的炉次
      // 表格滚动提示
      showScrollHint: false,
    };
  },
  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },
    // 总计划量计算（配料计划中的总重量）
    totalPlanWeight() {
      return this.burdenTableData
        .reduce((total, item) => {
          return total + (parseFloat(item.materialWeight) || 0);
        }, 0)
        .toFixed(3);
    },
    // 总计划重量数值（用于计算占比）
    totalPlanWeightNum() {
      const total = this.burdenTableData.reduce((total, item) => {
        return total + (parseFloat(item.materialWeight) || 0);
      }, 0);
      return total || 1; // 避免除零，如果总重量为0则返回1
    },
  },
  async onLoad() {
    await this.loadProcessOptions(); // 加载工序选项
    this.loadCurrentProcess(); // 加载当前工序
    // 页面加载时初始化时间范围并加载数据
    this.handleTimeChange("today");
    this.$nextTick(() => {
      this.handleSearch();
    });
  },
  methods: {
    /* 加载当前工序 */
    loadCurrentProcess() {
      // 尝试从用户配置中加载缓存的工序信息
      const userData = this.$store.state.user;
      const userConfig = userData.userConfig || {};
      if (userData && userData.userConfig) {
        const userConfig = userData.userConfig;
        // 从缓存中加载工序信息
        if (userConfig.processNo && userConfig.processName) {
          this.currentProcess = {
            processCode: userConfig.processNo,
            processName: userConfig.processName,
          };
          this.formData.processCode = userConfig.processNo;
          this.formData.processName = userConfig.processName;

          // 加载班次班组信息
          this.workShift = userConfig.workShift || "";
          this.workClass = userConfig.workClass || "";

          // 在工序选项中找到对应的索引
          const processIndex = this.processOptions.findIndex(
            (item) => item.value === userConfig.processNo
          );
          if (processIndex !== -1) {
            this.currentProcessIndex = processIndex;
          }
          return;
        }
      }

      // 如果没有缓存或缓存无效，默认选择第一个工序
      if (this.processOptions.length > 0) {
        this.currentProcess = {
          processCode: this.processOptions[0].value,
          processName: this.processOptions[0].text,
        };
        this.formData.processCode = this.currentProcess.processCode;
        this.formData.processName = this.currentProcess.processName;
        this.currentProcessIndex = 0;
      }
    },

    // 加载工序选项
    async loadProcessOptions() {
      try {
        const options = await getProcessOptions();
        this.processOptions = options;
        console.log("生产工序选项加载成功:", this.processOptions);
      } catch (error) {
        // 静默处理错误
        console.error("加载工序选项失败:", error);
        this.processOptions = [];
      }
    },

    /* 处理工序选择变化 */
    handleProcessChange(e) {
      const index = e.detail.value;
      this.currentProcessIndex = index;
      const selectedProcess = this.processOptions[index];
      if (selectedProcess) {
        this.currentProcess = {
          processCode: selectedProcess.value,
          processName: selectedProcess.text,
        };
        this.formData.processCode = selectedProcess.value;
        this.formData.processName = selectedProcess.text;

        // 重新搜索数据
        this.handleSearch();
      }
    },

    /* 下拉刷新 = 重置 */
    onPullDownRefresh() {
      // 重置所有相关状态
      this.furnaceTableData = [];
      this.hasMore = true;
      this.pageNum = 1;
      this.refreshing = true;

      // 停止刷新状态
      setTimeout(() => {
        this.refreshing = false;
      }, 500);

      // 重新初始化时间范围并搜索 - 使用重置模式
      this.handleTimeChange(this.timeFilter);
      this.$nextTick(() => {
        this.handleSearch(false); // 明确传递false，确保是重置而不是加载更多
      });
    },
    /* 触底加载 */
    onReachBottom() {
      if (this.loading) return;
      this.pageNum++;
      this.handleSearch(true);
    },
    /* 搜索主表 */
    async handleSearch(loadMore = false) {
      if (!loadMore) {
        this.furnaceTableData = [];
        this.hasMore = true;
        this.pageNum = 1;
      }
      this.loading = true;

      // 构建查询参数
      const params = {
        pageNo: this.pageNum, // 注意：有些后端接口使用pageNo而不是pageNum
        pageSize: 20,
        processName: this.currentProcess.processName || "",
      };
      // 只有在时间范围有效时才添加时间参数
      if (this.timeRange.startTime && this.timeRange.endTime) {
        params.createTime = [this.timeRange.startTime, this.timeRange.endTime];
      }

      try {
        const response = await SxBatchApi.getSxBatchPage(params);
        console.log("response:", response.data);
        if (response.code === 0) {
          // 数据去重处理 - 使用复合键唯一标识一条记录
          const newData = response.data.list;

          if (loadMore && newData.length === 0) {
            // 加载更多但没有新数据，说明已经到底了
            this.hasMore = false;
            uni.showToast({
              title: "没有更多数据了",
              icon: "none",
            });
          } else {
            this.furnaceTableData.push(...newData);
            this.hasMore = response.data.list.length === 10;
          }
        } else {
          uni.showToast({
            title: response.message || "加载数据失败",
            icon: "none",
          });
        }
      } catch (error) {
        uni.showToast({
          title: "请求失败: " + error.message,
          icon: "none",
        });
      }

      setTimeout(() => {
        this.loading = false;
      }, 600);
    },

    /* 选中炉次计划 */
    selectFurnace(furnaceItem) {
      this.selectedFurnace = furnaceItem;
      this.activeTab = "burden";
      this.loadBurdenData(furnaceItem.recordNo);
    },

    /* 加载配料数据 */
    async loadBurdenData(furnaceNo) {
      if (!furnaceNo) {
        this.burdenTableData = [];
        return;
      }

      try {
        //实际API调用示例（需要根据实际情况调整）：
        const response = await SxBatchApi.getSxBatchDetailListByRecordNo(
          furnaceNo
        );
        if (response.code === 0) {
          this.burdenTableData = response.data;
        }
      } catch (error) {
        console.error("加载配料数据失败:", error);
        this.burdenTableData = [];
      }
    },
    /* 时间选择处理 */
    handleTimeChange(timeFilter) {
      // 更新时间筛选器
      this.timeFilter = timeFilter;

      // 使用通用的updateDateRange函数
      const result = dateHelperApi.updateDateRange(timeFilter, {
        callback: ({ startDate, endDate }) => {
          // 更新时间范围
          this.timeRange = {
            startTime: startDate,
            endTime: endDate,
          };
        },
      });
    },

    /* 计算占比：当前重量 / 总计划重量 * 100 */
    calculateProportion(materialWeight) {
      if (!materialWeight || this.totalPlanWeightNum === 0) {
        return 0;
      }
      const currentWeight = parseFloat(materialWeight) || 0;
      const proportion = (currentWeight / this.totalPlanWeightNum) * 100;
      return proportion > 100 ? 100 : proportion; // 限制最大值为100%
    },

    /**
     * 处理表格滚动事件
     */
    handleTableScroll(event) {
      const scrollLeft = event.detail.scrollLeft;
      const scrollWidth = event.detail.scrollWidth;
      const clientWidth = event.detail.clientWidth;

      // 当可以横向滚动时显示提示
      if (scrollWidth > clientWidth) {
        // 滚动到最右边时隐藏提示
        if (scrollLeft >= scrollWidth - clientWidth - 10) {
          this.showScrollHint = false;
        } else {
          this.showScrollHint = true;
        }
      } else {
        this.showScrollHint = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/pages/smart/scss/create.scss";

/* 自定义样式 - 与create.scss中的通用样式配合使用 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.statistics-info {
  display: flex;
  gap: 30rpx;
}

.stat-item {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
}

/* 工序选择器容器 */
.process-picker-container {
  flex: 1;
  margin-left: 20rpx;
}

/* 工序选择器样式 */
.process-picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
  padding: 20rpx 24rpx;
  border-radius: 12rpx;
  border: 2rpx solid #e1e5e9;
  min-height: 80rpx;
  transition: all 0.3s ease;
}

.process-picker:active {
  background-color: #f8f9fa;
  border-color: #007aff;
}

/* 工序显示文本 */
.process-display {
  flex: 1;
  font-size: 30rpx;
  color: #333333;
  font-weight: 500;
  text-align: center;
  margin-right: 16rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 下拉箭头 */
.picker-arrow {
  color: #007aff;
  font-size: 28rpx;
  font-weight: bold;
  transition: transform 0.3s ease;
}

/* 表单项目样式优化 */
.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 0 20rpx;
}

.form-label {
  font-size: 32rpx;
  color: #333333;
  font-weight: 600;
  margin-right: 20rpx;
  min-width: 120rpx;
  white-space: nowrap;
}

/* Tab切换样式 - 继承create.scss中的通用样式并做微调 */
.tab-container {
  margin: 20rpx 0;
}

.tab-header {
  display: flex;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  padding: 8rpx;
  margin: 0 30rpx 20rpx;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 30rpx;
  color: #666;
  border-radius: 8rpx;
  transition: all 0.3s ease;
  cursor: pointer;
}

.tab-item.active {
  background-color: #007aff;
  color: #fff;
  font-weight: 600;
}

.tab-content {
  padding: 0 30rpx;
}

/* 有全新料重的行样式 - 淡绿色背景 */
.table-row.has-new-material {
  background-color: #e8f5e9 !important;
}

.table-row.has-new-material .table-cell {
  background-color: inherit;
}

/* 表格滚动容器 */
.table-scroll-container {
  overflow-x: auto;
  background-color: #fff;
}

/* 表格滚动提示 */
.scroll-hint {
  text-align: center;
  padding: 20rpx;
  font-size: 24rpx;
  color: #999;
  background-color: #f9f9fa;
  border-bottom: 1rpx solid #e5e5e5;
}

/* 表格样式 */
.table-content {
  min-width: 1200rpx;
}

/* 炉次计划表格字体优化 */
.tab-content .table-scroll {
  .table-row.header {
    .header-cell,
    .table-cell {
      font-size: 32rpx !important;
      font-weight: 700;
      padding: 20rpx 12rpx;
      min-height: 90rpx;
    }
  }

  .table-row:not(.header) {
    .table-cell {
      font-size: 30rpx !important;
      font-weight: 500;
      padding: 18rpx 12rpx;
      min-height: 85rpx;
      color: #1a1a1a;
    }
  }
}

/* 炉次信息提示 */
.furnace-info {
  margin: 20rpx 0;
  padding: 20rpx 24rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12rpx;
}

.furnace-info-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12rpx;
}

.furnace-info-text {
  font-size: 28rpx;
  color: #ffffff;
  font-weight: 600;
}

.furnace-extra-info {
  display: flex;
  gap: 30rpx;
  flex-wrap: wrap;
  justify-content: center;
}

.furnace-extra-item {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

/* 配料计划卡片容器 */
.burden-scroll {
  max-height: calc(100vh - 400rpx);
  padding-bottom: 20rpx;
}

/* 配料卡片样式 */
.burden-card {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  border: 1rpx solid #f0f0f0;
  transition: all 0.3s ease;
}

.burden-card:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.12);
}

/* 物料名称头部 */
.material-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #f5f5f5;
}

.material-name {
  font-size: 36rpx;
  font-weight: 700;
  color: #1a1a1a;
  flex: 1;
  letter-spacing: 1rpx;
}

.material-proportion-badge {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
  font-size: 24rpx;
  font-weight: 600;
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  min-width: 80rpx;
  text-align: center;
}

/* 主要信息区域 */
.material-main-info {
  margin-bottom: 24rpx;
}

/* 重量展示区域 */
.weight-section {
  display: flex;
  align-items: baseline;
  margin-bottom: 24rpx;
  padding: 20rpx;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 12rpx;
}

.weight-label {
  font-size: 28rpx;
  color: #666;
  margin-right: 16rpx;
  font-weight: 500;
}

.weight-value {
  font-size: 48rpx;
  font-weight: 700;
  color: #1a1a1a;
  letter-spacing: 2rpx;
  margin-right: 8rpx;
}

.weight-unit {
  font-size: 28rpx;
  color: #666;
  font-weight: 600;
}

/* 占比区域 */
.proportion-section {
  margin-top: 20rpx;
}

.proportion-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.proportion-label {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
}

.proportion-value {
  font-size: 32rpx;
  font-weight: 700;
  color: #667eea;
}

/* 占比进度条 */
.proportion-bar {
  width: 100%;
  height: 16rpx;
  background: #e8e8e8;
  border-radius: 8rpx;
  overflow: hidden;
  position: relative;
}

.proportion-fill {
  height: 100%;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  border-radius: 8rpx;
  transition: width 0.6s ease;
  position: relative;
}

.proportion-fill::after {
  content: "";
  position: absolute;
  right: 0;
  top: 0;
  width: 4rpx;
  height: 100%;
  background: rgba(255, 255, 255, 0.8);
  box-shadow: 0 0 8rpx rgba(255, 255, 255, 0.6);
}

/* 空数据提示 */
.empty-tip {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 28rpx;
}
</style>
